<template>
  <div class="appointment-page">
    <!-- 头部导航栏 -->
    <van-nav-bar
      title="预约看房"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      class="nav-bar"
    />
    
    <van-skeleton :row="20" :loading="!apartmentDetailInfo?.id">
      <div class="page-container">
        <!-- 预约公寓 -->
        <div class="section apartment-section">
          <div class="section-title">
            <van-icon name="home-o" class="title-icon" />
            <span>预约公寓</span>
          </div>
          <div class="apartment-card-wrapper">
            <ApartmentCard :data="apartmentDetailInfo" class="apartment-card" />
          </div>
        </div>
        
        <!-- 预约信息 -->
        <div class="section form-section">
          <div class="section-title">
            <van-icon name="edit" class="title-icon" />
            <span>预约信息</span>
          </div>
          <div class="form-wrapper">
            <van-form @submit="onSubmit" class="appointment-form">
              <van-cell-group inset class="form-group">
                <!-- 姓名 -->
                <van-field
                  v-model.trim="formData.name"
                  name="name"
                  label="姓名"
                  autocomplete="off"
                  placeholder="请输入姓名"
                  :rules="[{ required: true, message: '请填写姓名' }]"
                  class="form-field"
                />
                <!-- 手机号 -->
                <van-field
                  v-model.trim="formData.phone"
                  name="phone"
                  label="手机号"
                  type="tel"
                  autocomplete="off"
                  placeholder="请输入手机号"
                  :rules="[
                    {
                      required: true,
                      pattern: /^1([3589]\d|4[5-9]|6[1-2,4-7]|7[0-8])\d{8}$/,
                      message: '请正确填写手机号'
                    }
                  ]"
                  class="form-field"
                />
                <!-- 预约日期 -->
                <van-field
                  v-model="formData.date"
                  is-link
                  readonly
                  name="date"
                  label="预约日期"
                  placeholder="点击选择日期"
                  @click="showDate = true"
                  :rules="[{ required: true, message: '请选择预约日期' }]"
                  class="form-field"
                />
                <van-popup v-model:show="showDate" position="bottom" class="date-popup">
                  <van-date-picker
                    :min-date="new Date()"
                    @confirm="onConfirmAppointmentDateHandle"
                    @cancel="showDate = false"
                  />
                </van-popup>
                <!-- 预约时间 -->
                <van-field
                  v-model="formData.time"
                  is-link
                  readonly
                  name="time"
                  label="预约时间"
                  placeholder="点击选择时间"
                  @click="showTime = true"
                  :rules="[{ required: true, message: '请选择预约时间' }]"
                  class="form-field"
                />
                <van-popup v-model:show="showTime" position="bottom" class="time-popup">
                  <van-time-picker
                    v-model="dateInfo.time"
                    title="选择时间"
                    @confirm="onConfirmAppointmentTimeHandle"
                    @cancel="showTime = false"
                    :columns-type="['hour', 'minute', 'second']"
                  />
                </van-popup>
                <!-- 备注信息 -->
                <van-field
                  v-model.trim="formData.additionalInfo"
                  name="additionalInfo"
                  label="备注信息"
                  rows="3"
                  autosize
                  type="textarea"
                  autocomplete="off"
                  placeholder="请输入备注信息"
                  show-word-limit
                  maxlength="50"
                  class="form-field textarea-field"
                />
              </van-cell-group>
              
              <div class="submit-wrapper">
                <van-button 
                  round 
                  block 
                  type="primary" 
                  native-type="submit"
                  class="submit-button"
                  size="large"
                >
                  {{ formData.id ? "重新预约" : "预约看房" }}
                </van-button>
              </div>
            </van-form>
          </div>
        </div>
      </div>
    </van-skeleton>
  </div>
</template>
<script setup lang="ts">
import {
  getApartmentDetailById,
  getAppointmentDetailById,
  saveOrUpdateAppointment
} from "@/api/search";
import { onMounted, ref, watch } from "vue";
import dayjs from "dayjs";
import type {
  ApartmentInterface,
  AppointmentQueryInterface
} from "@/api/search/types";
import { useRoute, useRouter } from "vue-router";
import ApartmentCard from "@/components/ApartmentCard/ApartmentCard.vue";
import { AppointmentStatus } from "@/enums/constEnums";
import { showToast } from "vant";
const route = useRoute();
const router = useRouter();

// 返回按钮处理
const onClickLeft = () => {
  router.back();
};
// 公寓的详情信息
const apartmentDetailInfo = ref<ApartmentInterface>({} as ApartmentInterface);
// 获取公寓的详情信息
const getApartmentDetailHandle = async () => {
  const { data } = await getApartmentDetailById(
    route.query.apartmentId as string
  );
  apartmentDetailInfo.value = data;
};
//#region <form表单相关>
const formData = ref<
  AppointmentQueryInterface & { date: string; time: string }
>({
  id: "",
  name: "",
  phone: "",
  apartmentId: (route.query.apartmentId as string) || "",
  appointmentTime: "",
  additionalInfo: "",
  appointmentStatus: AppointmentStatus.WAITING,
  date: "",
  time: ""
});
// 日期选择器
const dateInfo = ref({
  date: [
    dayjs().get("year").toString(),
    (dayjs().get("month") + 1).toString().padStart(2, "0"),
    dayjs().get("date").toString().padStart(2, "0")
  ],
  time: [
    dayjs().get("hour").toString().padStart(2, "0"),
    dayjs().get("minute").toString().padStart(2, "0"),
    dayjs().get("second").toString().padStart(2, "0")
  ]
});
// 监视dateInfo
watch(
  dateInfo,
  (newVal, oldVal) => {
    console.log("newVal", newVal);
    console.log("oldVal", oldVal);
    formData.value.date = newVal.date.join("-");
    formData.value.time = `${newVal.time.join(":")}`;
    formData.value.appointmentTime = `${formData.value.date} ${formData.value.time}`;
  },
  { immediate: true, deep: true }
);
const showDate = ref(false);
const onConfirmAppointmentDateHandle = (date: any) => {
  console.log("date", date);
  dateInfo.value.date = date.selectedValues;
  showDate.value = false;
};
// 时间选择器
const showTime = ref(false);
const onConfirmAppointmentTimeHandle = (date: any) => {
  console.log("date", date);
  showTime.value = false;
};
// 提交表单
async function onSubmit(values: any) {
  console.log("submit", values);
  await saveOrUpdateAppointment(formData.value);
  showToast("操作成功");
  route.query.apartmentId
    ? await router.replace("/myAppointment")
    : await router.back();
}

//#endregion
// 预约信息
async function getAppointmentDetailHandle() {
  const { data } = await getAppointmentDetailById(
    route.query.appointmentId as string
  );
  Object.keys(formData.value).forEach(key => {
    (formData.value as any)[key] = (data as any)[key];
  });
  // 单独处理日期
  dateInfo.value.date = data.appointmentTime.split(" ")[0].split("-");
  dateInfo.value.time = data.appointmentTime.split(" ")[1].split(":");
  apartmentDetailInfo.value = data.apartmentItemVo;
}
onMounted(async () => {
  route.query.apartmentId && (await getApartmentDetailHandle());
  route.query.appointmentId && (await getAppointmentDetailHandle());
});
</script>

<style scoped lang="less">
.appointment-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  
  .nav-bar {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    :deep(.van-nav-bar__title) {
      color: white;
      font-weight: 600;
      font-size: 18px;
    }
    
    :deep(.van-nav-bar__left) {
      color: white;
    }
    
    :deep(.van-icon) {
      color: white;
    }
  }
  
  .page-container {
    padding: 16px;
    padding-bottom: 100px;
  }
  
  .section {
    margin-bottom: 20px;
    animation: fadeInUp 0.6s ease-out;
    
    &.apartment-section {
      animation-delay: 0.1s;
    }
    
    &.form-section {
      animation-delay: 0.2s;
    }
  }
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding: 0 4px;
    
    .title-icon {
      margin-right: 8px;
      color: #667eea;
      font-size: 18px;
    }
    
    span {
      font-size: 16px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .apartment-card-wrapper {
    .apartment-card {
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      overflow: hidden;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      }
    }
  }
  
  .form-wrapper {
    .form-group {
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      background: white;
      
      :deep(.van-cell-group) {
        background: transparent;
      }
      
      :deep(.van-cell) {
        background: white;
        border-bottom: 1px solid #f0f0f0;
        transition: background-color 0.3s ease;
        
        &:hover {
          background-color: #f8f9fa;
        }
        
        &:last-child {
          border-bottom: none;
        }
      }
      
      .form-field {
        :deep(.van-field__label) {
          color: #2c3e50;
          font-weight: 500;
          width: 80px;
        }
        
        :deep(.van-field__control) {
          color: #34495e;
        }
        
        :deep(.van-field__control::placeholder) {
          color: #bdc3c7;
        }
        
        &.textarea-field {
          :deep(.van-field__control) {
            min-height: 80px;
          }
        }
      }
    }
  }
  
  .submit-wrapper {
    margin-top: 32px;
    padding: 0 16px;
    
    .submit-button {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      height: 50px;
      font-size: 16px;
      font-weight: 600;
      box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 30px rgba(102, 126, 234, 0.4);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
  
  // 弹窗样式
  .date-popup,
  .time-popup {
    :deep(.van-popup) {
      border-radius: 12px 12px 0 0;
    }
    
    :deep(.van-picker) {
      background: white;
    }
    
    :deep(.van-picker__toolbar) {
      background: #f8f9fa;
      border-bottom: 1px solid #e9ecef;
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 375px) {
  .appointment-page {
    .page-container {
      padding: 12px;
    }
    
    .section-title {
      span {
        font-size: 15px;
      }
    }
    
    .submit-wrapper {
      padding: 0 8px;
      
      .submit-button {
        height: 46px;
        font-size: 15px;
      }
    }
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  .appointment-page {
    background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
    
    .section-title span {
      color: #ecf0f1;
    }
    
    .form-wrapper .form-group {
      background: #34495e;
      
      :deep(.van-cell) {
        background: #34495e;
        border-bottom-color: #4a5f7a;
        
        &:hover {
          background-color: #3d566e;
        }
      }
      
      .form-field {
        :deep(.van-field__label) {
          color: #ecf0f1;
        }
        
        :deep(.van-field__control) {
          color: #bdc3c7;
        }
      }
    }
  }
}

// 保持原有样式兼容性
:deep(.van-card) {
  background: var(--van-background-2) !important;
}
</style>
